<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="库存ID" prop="inventoryId">
        <el-input
          v-model="queryParams.inventoryId"
          placeholder="请输入库存ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产批号" prop="batchNumber">
        <el-input
          v-model="queryParams.batchNumber"
          placeholder="请输入生产批号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产日期" prop="productionDate">
        <el-date-picker clearable
          v-model="queryParams.productionDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择生产日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="有效期" prop="expiryDate">
        <el-date-picker clearable
          v-model="queryParams.expiryDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择有效期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="入库时间" prop="storeDate">
        <el-date-picker clearable
          v-model="queryParams.storeDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择入库时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="供应商ID" prop="supplier">
        <el-input
          v-model="queryParams.supplier"
          placeholder="请输入供应商ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['store:store:add']"
        >入库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['store:store:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['store:store:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['store:store:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库明细ID" align="center" prop="storeId" />
      <el-table-column label="药品名称" align="center" prop="drugName" /> <!-- 新增列 -->
      <el-table-column label="药品ID" align="center" prop="drugId" v-if="false"/> <!-- 隐藏原始ID列 -->
      <el-table-column label="入库数量" align="center" prop="stockQuantity" />
      <el-table-column label="生产批号" align="center" prop="batchNumber" />
      <el-table-column label="生产日期" align="center" prop="productionDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" prop="expiryDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expiryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入库时间" align="center" prop="storeDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.storeDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商ID" align="center" prop="supplier" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['store:store:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['store:store:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入库对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="storeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="库存ID" prop="inventoryId">
          <el-autocomplete
            v-model="batchNumberQuery"
            :fetch-suggestions="searchInventory"
            placeholder="请输入库存批号"
            value-key="batchNumber"
            @select="handleInventorySelect"
            clearable
          >
          <template #default="{ item }">
              <div>{{ item.batchNumber }} - 药物:({{ item.drugName }}) -库存数量:({{ item.stockQuantity }})</div>
            </template>
          </el-autocomplete>
        </el-form-item>


        <el-form-item label="药品名称" prop="drugId">
          <el-autocomplete
            v-model="drugNameQuery"
            :fetch-suggestions="searchDrugs"
            placeholder="请输入药品名称"
            value-key="drugName"
            @select="handleDrugSelect"
            :disabled="!!form.inventoryId" 
            clearable
          >
            <template #default="{ item }">
              <div>{{ item.drugName }} - 单位:({{ item.unit }}) -规格:({{ item.spec }})</div>
            </template>
          </el-autocomplete>
        </el-form-item>


        <el-form-item label="入库数量" prop="stockQuantity">
          <el-input v-model="form.stockQuantity" placeholder="请输入入库数量" />
        </el-form-item>
        <el-form-item label="存放位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入存放位置" :disabled="!!form.inventoryId" />
        </el-form-item>
        <el-form-item label="生产批号" prop="batchNumber">
          <el-input v-model="form.batchNumber" placeholder="请输入生产批号" :disabled="!!form.inventoryId" />
        </el-form-item>
        <el-form-item label="入库方式" prop="way">
          <el-input v-model="form.way" placeholder=" 请输入入库方式" />
        </el-form-item>
        <el-form-item label="入库人员" prop="storeAdmin">
          <el-input v-model="form.storeAdmin" placeholder=" 请输入入库人员" />
        </el-form-item>


       
        <el-form-item label="生产日期" prop="productionDate"  >
          <el-date-picker clearable
            v-model="form.productionDate"
            type="date"
            value-format="YYYY-MM-DD"
            :disabled="!!form.inventoryId" 
            placeholder="请选择生产日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期" prop="expiryDate"  >
          <el-date-picker clearable
            v-model="form.expiryDate"
            type="date"
            value-format="YYYY-MM-DD"
            :disabled="!!form.inventoryId" 
            placeholder="请选择有效期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="入库时间" prop="storeDate"  >
          <el-date-picker clearable
            v-model="form.storeDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择入库时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应商ID" prop="supplier">
          <el-input v-model="form.supplier" placeholder="请输入供应商ID" :disabled="!!form.inventoryId" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Store">
import { listStore, getStore, delStore, addStore, updateStore } from "@/api/store/store";
import { listDrugs } from "@/api/drugs/drugs"; // 新增药品接口引用
import { listInventory } from "@/api/inventory/inventory"; // 新增药品库存接口引用


const { proxy } = getCurrentInstance();
const drugNameQuery = ref('');
const batchNumberQuery = ref('');
const storeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    inventoryId: null,
    batchNumber: null,
    productionDate: null,
    expiryDate: null,
    drugId: null,
    supplier: null,
    storeDate:null,
  },
  rules: {
    drugId: [
      { required: true, message: "药品ID不能为空", trigger: "change" }
    ],
    stockQuantity: [
      { required: true, message: "入库数量不能为空", trigger: "blur" }
    ],
    batchNumber: [
      { required: true, message: "生产批号不能为空", trigger: "blur" }
    ],
    productionDate: [
      { required: true, message: "生产日期不能为空", trigger: "blur" }
    ],
    expiryDate: [
      { required: true, message: "有效期不能为空", trigger: "blur" }
    ],
    storeDate: [
      { required: true, message: "入库时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 药品库存搜索方法 */
const searchInventory = async (queryString, cb) => {
  if (!queryString) {
    cb([]);
    return;
  }
  try {
    const res = await listInventory({
      pageNum: 1,
      pageSize: 10,
      batchNumber: queryString
    });
    cb(res.rows);
  } catch {
    cb([]);
  }
};


/** 药品搜索方法 */
const searchDrugs = async (queryString, cb) => {
  if (!queryString) {
    cb([]);
    return;
  }
  try {
    const res = await listDrugs({
      pageNum: 1,
      pageSize: 10,
      drugName: queryString
    });
    cb(res.rows);
  } catch {
    cb([]);
  }
};



const handleInventorySelect = (item) => {
  form.value.inventoryId = item.inventoryId;
  form.value.drugId = item.drugId;
  // 将库存信息中的相关字段赋值到表单
  form.value.batchNumber = item.batchNumber;
  form.value.productionDate = item.productionDate;
  form.value.expiryDate = item.expiryDate;
  form.value.supplier = item.supplier;
  form.value.location = item.location;
  form.value.way = "补录入库";
  // 更新显示的药品名称和批号查询条件
  drugNameQuery.value = item.drugName;
  batchNumberQuery.value = item.batchNumber;
};


const handleDrugSelect = (item) => {
  form.value.drugId = item.drugId;          // 绑定药品ID
  drugNameQuery.value = item.drugName;      // 更新药品名称显示
};


/** 查询入库列表 */
function getList() {
  loading.value = true;
  listStore(queryParams.value).then(response => {
    storeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  drugNameQuery.value = '';
  batchNumberQuery.value = '';
  reset();
}

// 表单重置
function reset() {
  form.value = {
    storeId: null,
    inventoryId: null,
    drugId: null,
    stockQuantity: null,
    location: null,
    batchNumber: null,
    productionDate: null,
    expiryDate: null,
    supplier: null
  };
  proxy.resetForm("storeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.storeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加入库";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _storeId = row.storeId || ids.value
  getStore(_storeId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改入库";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["storeRef"].validate(valid => {
    if (valid) {
      if (form.value.storeId != null) {
        updateStore(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addStore(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _storeIds = row.storeId || ids.value;
  proxy.$modal.confirm('是否确认删除入库编号为"' + _storeIds + '"的数据项？').then(function() {
    return delStore(_storeIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('store/store/export', {
    ...queryParams.value
  }, `store_${new Date().getTime()}.xlsx`)
}

getList();
</script>
